package com.qujia.station.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.common.utils.sql.SqlUtil;
import com.qujia.station.domain.*;
import com.qujia.station.domain.dto.AddTeamManagement;
import com.qujia.station.domain.dto.RegionalReportDto;
import com.qujia.station.domain.dto.TeamManagementDto;
import com.qujia.station.domain.vo.DistrictEnterpriseVo;
import com.qujia.station.domain.vo.RegionalReportVo;
import com.qujia.station.domain.vo.TeamManagementVo;
import com.qujia.station.mapper.PayOrderHistoryMapper;
import com.qujia.station.mapper.PayOrderMapper;
import com.qujia.station.mapper.TeamManagementMapper;
import com.qujia.station.service.*;
import com.qujia.station.utils.PermissionsUtil;
import com.qujia.system.service.ISysUserService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.github.pagehelper.page.PageMethod.startPage;

/**
 * @author PC
 * @description 针对表【team_management(团队管理表)】的数据库操作Service实现
 * @createDate 2023-08-29 16:32:10
 */
@Service
@Slf4j
public class TeamManagementServiceImpl extends ServiceImpl<TeamManagementMapper, TeamManagement>
        implements TeamManagementService {

    @Autowired
    private MemberManagementService memberManagementService;

    @Autowired
    private TeamManagementMapper teamManagementMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private IStationService stationService;

//    @Autowired
//    private IPayOrderService payOrderService;

    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private PayOrderHistoryMapper payOrderHistoryMapper;
    @Override
    @Transactional
    @SneakyThrows
    public AddTeamManagement addTeam(AddTeamManagement addTeamManagement) {
        if (ObjectUtils.isEmpty(addTeamManagement)) {
            throw new Exception("参数为空，请排查");
        }
        TeamManagement teamManagement = new TeamManagement();
        BeanUtils.copyProperties(addTeamManagement, teamManagement);

        if (null != addTeamManagement.getLeaderId()) {
            SysUser sysUser = sysUserService.selectUserById(addTeamManagement.getLeaderId());

            if (!UserConstants.LEVEL_FIVE.equals(sysUser.getUserLevel())) {
                throw new CustomException("当前用户不是区域经理");
            }
            teamManagement.setLeader(sysUser.getNickName());

            TeamManagementVo teamManagementVo = teamManagementMapper.selectByLeader(addTeamManagement.getLeaderId());
            if (ObjectUtils.isNotEmpty(teamManagementVo)) {
                throw new CustomException("该用户已为区域负责人，不可重复设置");
            }
        }

        if (CollectionUtil.isNotEmpty(addTeamManagement.getMember())) {
            teamManagement.setMembers(String.join(",", addTeamManagement.getMember()));
        }

        TeamManagementVo repeat = teamManagementMapper.repeat(teamManagement.getTeamName());
        if (ObjectUtils.isNotEmpty(repeat)) {
            throw new CustomException("重复团队名称");
        }

        if (null != addTeamManagement.getDistrict()) {
            String getdistrict = getdistrict(addTeamManagement.getDistrict());
            teamManagement.setDistrict(getdistrict);
        }
        log.info("新增团队：{}", teamManagement);
        teamManagementMapper.insert(teamManagement);
        //更改成员信息
        if (CollectionUtil.isNotEmpty(addTeamManagement.getMember())) {

            log.info("获取成员信息：{}", addTeamManagement.getMember());
            for (String id : addTeamManagement.getMember()) {

                SysUser sysUser1 = sysUserService.selectUserById(Long.valueOf(id));
                MemberManagement memberManagement = memberManagementService.selectBySalesmanId(Long.valueOf(id));

                if (ObjectUtils.isEmpty(sysUser1) || !sysUser1.getStatus().equals("0") || !sysUser1.getUserLevel().equals("6")) {
                    throw new CustomException("该成员状态或者等级不正确，请排查");
                }
                MemberManagement management = MemberManagement.builder()
                        .salesmanId(Long.valueOf(id))
                        .teamId(teamManagement.getId())
                        .updateTime(new Date())
                        .build();
                log.info("更改成员信息：成员id：{},团队id：{}", id, teamManagement.getId());
                memberManagementService.updateBySalesmanId(management);
//                if (ObjectUtils.isNotEmpty(memberManagement)) {
//                    if (Objects.nonNull(memberManagement.getTeamId())) {
//                        //删除之前在团队的业务员id
//                        this.updateTeamMemberId(memberManagement.getTeamId(), Long.valueOf(id));
//                    }
//                }
            }
        }
        return addTeamManagement;
    }

    @Override
    @Transactional
    @SneakyThrows
    public void deleteTeamManagement(String ids) {
        List<String> teamIds = Arrays.asList(ids.split(","));
        for (String teamId : teamIds) {
            log.info("删除团队id{}", teamId);

            teamManagementMapper.deleteByTeamId(Long.valueOf(teamId), DateUtil.now());
            //解绑该团队绑定的成员
            memberManagementService.updateMemberManagement(null, Long.valueOf(teamId));
        }
    }

    // if (null != addTeamManagement.getLeaderId()){
//        SysUser sysUser = sysUserService.selectUserById(addTeamManagement.getLeaderId());
//
//        if (!UserConstants.LEVEL_FIVE.equals(sysUser.getUserLevel())) {
//            throw new CustomException("当前用户不是区域经理");
//        }
//        teamManagement.setLeader(sysUser.getNickName());
//        if (!addTeamManagement.getMember().isEmpty()) {
//            teamManagement.setMembers(String.join(",", addTeamManagement.getMember()));
//        }
//        TeamManagementVo teamManagementVo = teamManagementMapper.selectByLeader(addTeamManagement.getLeaderId());
//        if (ObjectUtils.isNotEmpty(teamManagementVo)) {
//            throw new CustomException("该用户已为区域负责人，不可重复设置");
//        }
//    }
//
//    Integer repeat = teamManagementMapper.repeat(teamManagement.getTeamName());
//        if (repeat > 0){
//        throw new CustomException("重复团队名称");
//    }
    @Override
    @Transactional
    @SneakyThrows
    public AddTeamManagement updateTeamManagement(AddTeamManagement addTeamManagement) {
        TeamManagement teamManagement = new TeamManagement();
        log.info("修改团队参数：{}", addTeamManagement);
        BeanUtils.copyProperties(addTeamManagement, teamManagement);
        if (null != addTeamManagement.getLeaderId()) {
            log.info("获取负责人信息：{}", addTeamManagement.getLeaderId());
            SysUser sysUser = sysUserService.selectUserById(addTeamManagement.getLeaderId());
            if (ObjectUtils.isEmpty(sysUser) || !UserConstants.LEVEL_FIVE.equals(sysUser.getUserLevel())) {
                throw new CustomException("没有获取到负责人信息或者当前用户等级不是五级区域经理");
            }
            TeamManagementVo teamManagementVo = teamManagementMapper.selectByLeader(addTeamManagement.getLeaderId());
            if (ObjectUtils.isNotEmpty(teamManagementVo) && !addTeamManagement.getId().equals(teamManagementVo.getId())) {
                throw new CustomException("该用户已为区域负责人，不可重复设置");
            }
            teamManagement.setLeader(sysUser.getNickName());

        }
        if (CollectionUtil.isNotEmpty(addTeamManagement.getMember())) {
            List<String> members = addTeamManagement.getMember();
            String member = StringUtils.join(members, ",");
            teamManagement.setMembers(member);
        }

        if (addTeamManagement.getDistrict() != null) {
            String getdistrict = getdistrict(addTeamManagement.getDistrict());
            teamManagement.setDistrict(getdistrict);
        }

        TeamManagementVo repeat = teamManagementMapper.repeat(teamManagement.getTeamName());
        if (ObjectUtils.isNotEmpty(repeat) && !Objects.equals(repeat.getId(), teamManagement.getId())) {
            throw new CustomException("重复团队名称");
        }


//        teamManagement.setUpdateTime(new Date());
//        teamManagementMapper.updateByTeamId(teamManagement);
        LambdaUpdateWrapper<TeamManagement> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        //eq是指你查询的条件，set是指你修改的值
        lambdaUpdateWrapper.eq(TeamManagement::getId, teamManagement.getId())
                .set(TeamManagement::getTeamName, teamManagement.getTeamName())
                .set(TeamManagement::getUpdateTime, new Date())
                .set(TeamManagement::getDistrict, teamManagement.getDistrict())
                .set(TeamManagement::getLeader, teamManagement.getLeader())
                .set(TeamManagement::getLeaderId, teamManagement.getLeaderId())
                .set(TeamManagement::getMembers, teamManagement.getMembers());
        this.update(lambdaUpdateWrapper);


        //更改成员信息
        //将这个团队之前的成员解绑
        memberManagementService.updateMemberManagement(null, teamManagement.getId());
        if (CollectionUtil.isNotEmpty(addTeamManagement.getMember())) {
            log.info("获取成员信息：id{}", addTeamManagement.getMember());
            //重新绑定
            for (String id : addTeamManagement.getMember()) {

                SysUser sysUser1 = sysUserService.selectUserById(Long.valueOf(id));
                MemberManagement memberManagement = memberManagementService.selectBySalesmanId(sysUser1.getUserId());

                if (ObjectUtils.isEmpty(memberManagement) || ObjectUtils.isEmpty(sysUser1) || !sysUser1.getStatus().equals("0") || !sysUser1.getUserLevel().equals("6")) {
                    throw new CustomException("该成员状态或者等级不正确，请排查");
                }

                MemberManagement management = MemberManagement.builder()
                        .salesmanId(Long.valueOf(id))
                        .teamId(teamManagement.getId())
                        .updateTime(new Date())
                        .build();
                memberManagementService.updateBySalesmanId(management);

            }
        }
        return addTeamManagement;
    }

    @Override
    public List<TeamManagementVo> selectTeamManagement(TeamManagementDto teamManagementDto) {

        List<TeamManagementVo> teamManagementVos = teamManagementMapper.selectTeamList(teamManagementDto);

        for (TeamManagementVo teamManagementVo : teamManagementVos) {
            ArrayList<SysUser> sysUsers = new ArrayList<>();

            //回传
            if (StringUtils.isNotEmpty(teamManagementVo.getDistrictName())) {
                String districtName = teamManagementVo.getDistrictName();
                Integer District = getdistrictName(districtName);
                teamManagementVo.setDistrict(District);
            }


            if (StringUtils.isEmpty(teamManagementVo.getMembers())) {
                continue;
            }
            String members = teamManagementVo.getMembers();
            for (String memberId : members.split(",")) {
                //获取成员信息
                SysUser sysUser = sysUserService.selectUserById(Long.valueOf(memberId));
                sysUsers.add(sysUser);
            }
            teamManagementVo.setMemberInfos(sysUsers);
        }
        return teamManagementVos;
    }

    @Override
    public List<Long> getManagerEnterpriseId(Long id) {
        //获取团队名下业务员管理的油企id
        ArrayList<Long> enterpriseIds = new ArrayList<>();
        String members = teamManagementMapper.selectByTeamIdOrLeaderId(id, null);
        if (StringUtils.isNotEmpty(members)) {
            String[] split = members.split(",");

            for (String memberId : split) {
                List<Long> memberEnterpriseId = memberManagementService.getMemberEnterpriseId(Long.valueOf(memberId));
                enterpriseIds.addAll(memberEnterpriseId);
            }
            //去重
            List<Long> newList = enterpriseIds.stream().distinct().collect(Collectors.toList());
            enterpriseIds.clear();
            enterpriseIds.addAll(newList);
        }
        return enterpriseIds;

    }

    @Override
    @Transactional
    public void updateTeamMemberId(Long teamId, Long salesmanId) {
        String memberId = teamManagementMapper.selectByTeamIdOrLeaderId(null, teamId);
        if (StringUtils.isEmpty(memberId)) {
            return;
        }
        String[] memberIds = memberId.split(",");

        ArrayList<String> list = new ArrayList<>(Arrays.asList(memberIds));

        list.removeIf(id -> id.equals(salesmanId.toString()));

        String collect = String.join(",", list);
        TeamManagement management = TeamManagement.builder()
                .id(teamId)
                .members(collect)
                .updateTime(new Date())
                .build();
        teamManagementMapper.updateById(management);
    }

    @Override
    public List<Long> getEnterpriseByDistrict(String district) {

        TeamManagementDto teamManagementDto = new TeamManagementDto();
        teamManagementDto.setDistrictName(district);
        List<TeamManagementVo> teamManagementVos = teamManagementMapper.selectTeamList(teamManagementDto);
        ArrayList<Long> enterpriseIds = new ArrayList<>();
        for (TeamManagementVo teamManagementVo : teamManagementVos) {
            Long teamId = teamManagementVo.getId();
            String members = teamManagementMapper.selectByTeamIdOrLeaderId(null, teamId);
            if (StringUtils.isNotEmpty(members)) {

                String[] split = members.split(",");
                //获取团队名下业务员管理的油企id
                for (String memberId : split) {
                    List<Long> memberEnterpriseId = memberManagementService.getMemberEnterpriseId(Long.valueOf(memberId));
                    enterpriseIds.addAll(memberEnterpriseId);
                }
            }
        }
        //去重
        List<Long> newList = enterpriseIds.stream().distinct().collect(Collectors.toList());
        enterpriseIds.clear();
        enterpriseIds.addAll(newList);
        return enterpriseIds;
    }

    @Override
    public List<DistrictEnterpriseVo> getEnterpriseId(Integer district) {
        LoginUser current = SecurityUtils.getLoginUser();
        SysUser user = current.getUser();
        ArrayList<DistrictEnterpriseVo> enterpriseVos = new ArrayList<>();
        if (UserConstants.LEVEL_FIVE.equals(user.getUserLevel())) {
            List<Long> managerEnterpriseId = getManagerEnterpriseId(user.getUserId());
            if (CollectionUtil.isNotEmpty(managerEnterpriseId)) {
                for (Long enterpriseId : managerEnterpriseId) {
                    Enterprise enterprise = enterpriseService.selectEnterpriseById(enterpriseId);
                    DistrictEnterpriseVo districtEnterpriseVo = new DistrictEnterpriseVo();
                    BeanUtils.copyProperties(enterprise, districtEnterpriseVo);
                    enterpriseVos.add(districtEnterpriseVo);
                }
                return enterpriseVos;
            }
        }
        if (UserConstants.LEVEL_SIX.equals(user.getUserLevel())) {
            List<Long> managerEnterpriseId = memberManagementService.getMemberEnterpriseId(user.getUserId());
            if (CollectionUtil.isNotEmpty(managerEnterpriseId)) {
                for (Long enterpriseId : managerEnterpriseId) {
                    Enterprise enterprise = enterpriseService.selectEnterpriseById(enterpriseId);
                    DistrictEnterpriseVo districtEnterpriseVo = new DistrictEnterpriseVo();
                    BeanUtils.copyProperties(enterprise, districtEnterpriseVo);
                    enterpriseVos.add(districtEnterpriseVo);
                }
                return enterpriseVos;
            }
        }
        if (UserConstants.LEVEL_ONE.equals(user.getUserLevel()) || StringUtils.isBlank(user.getUserLevel())) {
            if (null != district) {
                String districtName = getdistrict(district);
                List<Long> enterpriseByDistrict = getEnterpriseByDistrict(districtName);
                if (CollectionUtil.isNotEmpty(enterpriseByDistrict)) {
                    for (Long enterpriseId : enterpriseByDistrict) {
                        Enterprise enterprise = enterpriseService.selectEnterpriseById(enterpriseId);
                        DistrictEnterpriseVo districtEnterpriseVo = new DistrictEnterpriseVo();
                        BeanUtils.copyProperties(enterprise, districtEnterpriseVo);
                        enterpriseVos.add(districtEnterpriseVo);
                    }
                    return enterpriseVos;
                } else {
                    return enterpriseVos;
                }

            }
            Enterprise enterprise = new Enterprise();
            enterprise.setStatus("0");
            enterprise.setDeleteStatus("0");
            List<Enterprise> enterprises = enterpriseService.selectEnterpriseList(enterprise);
            for (Enterprise enterpriseInfo : enterprises) {
                DistrictEnterpriseVo districtEnterpriseVo = new DistrictEnterpriseVo();
                BeanUtils.copyProperties(enterpriseInfo, districtEnterpriseVo);
                enterpriseVos.add(districtEnterpriseVo);
            }
            return enterpriseVos;
        }
        return enterpriseVos;
    }

    @Override
    public List<RegionalReportVo> getRegionalReport(List<Integer> districtIds, String beginTime,String endTime,Integer pageNum,Integer pageSize,Integer sorted) {

        PayOrder payOrder = new PayOrder();
        payOrder.setBeginTime(beginTime);
        payOrder.setEndTime(endTime);
        ArrayList<String> EnterpriseIdList = new ArrayList<>();
        LinkedHashSet<String> EnterpriseIdListSet = new LinkedHashSet<>();
        if (CollectionUtil.isNotEmpty(districtIds)){
            for (Integer district : districtIds) {

                String districtName = PermissionsUtil.getDistrict(district);

                log.info("输入的地区,{}", districtName);
                List<Long> enterpriseByDistrict = getEnterpriseByDistrict(districtName);
                log.info("获得该地区的所有油企id：{}",enterpriseByDistrict);
                List<String>  enterpriseIds = enterpriseByDistrict.stream().map(x -> x + "").collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(enterpriseIds)){
                    EnterpriseIdList.addAll(enterpriseIds);
                } else {
                    if (CollectionUtil.isNotEmpty(payOrder.getEnterpriseIdList())){
                        break;
                    }
                    enterpriseIds.add("0");
                    EnterpriseIdList.addAll(enterpriseIds);
                }
            }
            CollectionUtil.addAll(EnterpriseIdListSet,EnterpriseIdList);
            CollectionUtil.addAll(EnterpriseIdList,EnterpriseIdListSet);
            payOrder.setEnterpriseIdList(EnterpriseIdList);
        }

        payOrder.setStatus("1");
        List<StatisticsPayOrder> statisticsPayOrders = payOrderMapper.newSelectStatisticsPayOrderList(payOrder);
        List<StatisticsPayOrder> SevenPayOrders  = payOrderHistoryMapper.newSelectStatisticsPayOrderHistoryList(payOrder);
        //将历史订单也查出合在一起
        statisticsPayOrders.addAll(SevenPayOrders);
        Map<Long, List<StatisticsPayOrder>> payOrderMap = statisticsPayOrders.stream().collect(Collectors.groupingBy(StatisticsPayOrder::getStationId));
        ArrayList<RegionalReportVo> regionalReportVos = new ArrayList<>();
        for (Long stationId : payOrderMap.keySet()) {
            BigDecimal amt = new BigDecimal("0.00");
            BigDecimal orderLiters = new BigDecimal("0.00");
            BigDecimal receivableAmt = new BigDecimal("0.00");
            BigDecimal receivedAmt = new BigDecimal("0.00");
            BigDecimal discountAmt = new BigDecimal("0.00");
            Integer countNum = 0;

            RegionalReportVo regionalReportVo = new RegionalReportVo();

            for (StatisticsPayOrder statisticsPayOrder : payOrderMap.get(stationId)) {
                amt = amt.add(statisticsPayOrder.getAmt());
                orderLiters = orderLiters.add(statisticsPayOrder.getOrderLiters());
                receivableAmt = receivableAmt.add(statisticsPayOrder.getReceivableAmt());
                receivedAmt = receivedAmt.add(statisticsPayOrder.getReceivedAmt());
                discountAmt = discountAmt.add(statisticsPayOrder.getDiscountAmt());
                countNum += statisticsPayOrder.getCountNum();

                regionalReportVo.setEnterpriseName(statisticsPayOrder.getEnterpriseName());
                regionalReportVo.setStationName(statisticsPayOrder.getStationName());
                regionalReportVo.setEnterpriseId(statisticsPayOrder.getEnterpriseId());
            }

            regionalReportVo.setSalesVolume(String.valueOf(amt));
            regionalReportVo.setOrderNumber(countNum);
            regionalReportVo.setQuantity(String.valueOf(orderLiters));
            regionalReportVo.setBeginTime(beginTime);
            regionalReportVo.setEndTime(endTime);
            regionalReportVos.add(regionalReportVo);
        }

        //给已经划分大区的油企赋值大区名称
        for (RegionalReportVo regionalReportVo : regionalReportVos) {
            String district = null;
            if (CollectionUtil.isEmpty(districtIds) || districtIds.size() > 1){
                district = memberManagementService.getDistrictByEnterpriseIdAndTeamId(regionalReportVo.getEnterpriseId(),districtIds);
            }else if (districtIds.size() == 1){
                    for (Integer districtId : districtIds) {
                        district = PermissionsUtil.getDistrict(districtId);
                    }
            }

            if (org.apache.commons.lang3.StringUtils.isNotBlank(district)) {
                regionalReportVo.setDistrict(district);
                //大区人数 加上区域经理
                Integer districtSum = 0;
                if (StringUtils.isNotEmpty(district)){
                    districtSum = getDistrictSum(district);
                    regionalReportVo.setDistrictPeopleNumber(districtSum);
                }
            }
        }

        //根据销售额排序
        regionalReportVos.sort(((o1,o2) -> {
            //从大到小
            BigDecimal o1Value = new BigDecimal(o1.getSalesVolume());
            BigDecimal o2Value = new BigDecimal(o2.getSalesVolume());
            return o2Value.compareTo(o1Value);
        }));


        for (RegionalReportVo newRegionalReportVo : regionalReportVos) {
            newRegionalReportVo.setRanking(regionalReportVos.indexOf(newRegionalReportVo)+1);
        }

        //根据排名排序
        List<RegionalReportVo> regionalReportVosRes;
        if (null == sorted || sorted.equals(1)){

            regionalReportVosRes = regionalReportVos.stream().sorted(Comparator.comparing(RegionalReportVo::getRanking).reversed()).collect(Collectors.toList());
        }else {

            regionalReportVosRes = regionalReportVos.stream().sorted(Comparator.comparing(RegionalReportVo::getRanking)).collect(Collectors.toList());
        }

        return regionalReportVosRes;
    }

    public String getdistrict(Integer district) {
        String districtString = "";
        switch (district) {
            case 1:
                districtString = "华北地区";
                break;
            case 2:
                districtString = "华南地区";
                break;
            case 3:
                districtString = "西南地区";
                break;
            case 4:
                districtString = "西北地区";
                break;
            case 5:
                districtString = "东北地区";
                break;
            default:
                throw new CustomException("传个正确的地区");
        }
        return districtString;
    }

    public Integer getdistrictName(String districtName) {
        Integer district = 0;
        switch (districtName) {
            case "华北地区":
                district = 1;
                break;
            case "华南地区":
                district = 2;
                break;
            case "西南地区":
                district = 3;
                break;
            case "西北地区":
                district = 4;
                break;
            case "东北地区":
                district = 5;
                break;
            default:
                throw new CustomException("传个正确的地区");
        }
        return district;
    }
    //获取该大区多少人数
    public Integer getDistrictSum(String district){
        TeamManagementDto te = TeamManagementDto.builder().districtName(district).build();
        List<TeamManagementVo> teamManagementVos = teamManagementMapper.selectTeamList(te);
        int sum = 0;
        if (CollectionUtil.isNotEmpty(teamManagementVos)){
            for (TeamManagementVo teamManagementVo : teamManagementVos) {
                String members = teamManagementVo.getMembers();
                if (StringUtils.isNotEmpty(members)){
                    String[] split = members.split(",");
                    int length = split.length;
                    sum += length;

                }
                Long leaderId = teamManagementVo.getLeaderId();
                if (null != leaderId){
                    sum += 1;
                }
            }
        }
        return sum;
    }

}




